package com.yr.ryjk.app.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yr.ryjk.app.dao.AppMapper;
import com.yr.ryjk.app.entity.App;
import com.yr.ryjk.common.ErrorType;
import com.yr.ryjk.common.Pagination;
import com.yr.ryjk.util.IDGenerator;
import com.yr.ryjk.util.JSONUtil;
import com.yr.ryjk.util.VersionComparator;

@Service
public class AppService implements IAppService{
	@Autowired
	private AppMapper appMapper;
	@Override
	public Map<String, Object> add(String version, String url, int status,String suName,int forceUpdate) {
		App appOldVersion = appMapper.selectLatestVersion();
		if(appOldVersion !=null){
			//判断版本号
			Boolean flag = VersionComparator.cpVersion(appOldVersion.getVersion(),version);
			if(flag){
				if(status==1){
					appMapper.updateSetUnDefault();
				}
				App app=new App();
				app.setId(IDGenerator.gen32UUID());
				app.setVersion(version);
				app.setUrl(url);
				app.setUploadTime(new Date());
				app.setUploadMan(suName);		
				app.setStatus(status);
				app.setForceUpdate(forceUpdate);
				
				appMapper.insert(app);
				return JSONUtil.getJSON(ErrorType.SUCCESS);
			}else{	
				return JSONUtil.getJSON(ErrorType.APP_VERSION_ERROR);
			}
		}else{
			App app=new App();
			app.setId(IDGenerator.gen32UUID());
			app.setVersion(version);
			app.setUrl(url);
			app.setUploadTime(new Date());
			app.setUploadMan(suName);		
			app.setStatus(status);
			app.setForceUpdate(forceUpdate);
			
			appMapper.insert(app);
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
	}

	@Override
	public Map<String, Object> getListOfPage(int pageNo, int pageSize,String version) {
		
		List<App> list=appMapper.selectOfPage((pageNo-1)*pageSize,pageSize,version);
		int count=appMapper.selectCount(version);
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("list", list);
		map.put("pagination", new Pagination(pageSize,pageNo,count));
		
		return map;
	}

	@Override
	public Map<String, Object> updateSetDefault(String id) {
		appMapper.updateSetUnDefault();
		appMapper.updateSetDefault(id);
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public App getLatestApp() {
		return appMapper.selectLatestVersion();
	}
}
